import { wrapperToken } from './utils'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './router'
import { useMenuStore } from './store/modules/menu'

const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken: string | undefined = wrapperToken.getToken()
  const menuStore = useMenuStore()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const hasMenus: boolean = Boolean(menuStore.getMenuList?.length)
      if (hasMenus) {
        next()
      } else {
        console.log(from)
        try {
          await menuStore.setMenuList()
          await menuStore.getMenuList.forEach(routeItem => {
            router.addRoute(routeItem)
          })
          next({ ...to, replace: true })
        } catch (error) {
          console.log(error)
        }
      }
    }
  } else if (whiteList.includes(to.path)) {
    next()
  } else {
    next('/login')
  }
})
router.afterEach(() => {
  NProgress.done()
})
